package handler

import (
	"context"
	"gitee.com/wendyRose/cart/domain/model"
	"gitee.com/wendyRose/cart/domain/service"
	"gitee.com/wendyRose/cart/proto/cart"
	"gitee.com/wendyRose/common"
)

type Cart struct{
	CartDataService service.ICartDataService
}

func (h *Cart) AddCart(ctx context.Context, request *cart.CartInfo, response *cart.ResponseAdd) (err error) {
	addCart := &model.Cart{}
	_ = common.SwapTo(request, addCart)
	response.CartId, err = h.CartDataService.AddCart(addCart)
	return err
}

func (h *Cart) CleanCart(ctx context.Context, request *cart.Clean, response *cart.Response) (err error) {
	if err := h.CartDataService.CleanCart(request.UserId); err != nil {
		return err
	}
	response.Msg = "购物车清空成功"
	return nil
}

func (h *Cart) Incr(ctx context.Context, request *cart.Item, response *cart.Response) (err error) {
	if err := h.CartDataService.IncrNum(request.Id, request.ChangeNum); err != nil {
		return err
	}
	response.Msg = "添加购物车成功"
	return nil
}

func (h *Cart) Decr(ctx context.Context, request *cart.Item, response *cart.Response) (err error) {
	if err := h.CartDataService.DecrNum(request.Id, request.ChangeNum); err != nil {
		return err
	}
	response.Msg = "删除购物车成功"
	return nil
}

func (h *Cart) DeleteItemById(ctx context.Context, request *cart.CartID, response *cart.Response) (err error) {
	if err := h.CartDataService.DeleteCart(request.Id); err != nil {
		return err
	}
	response.Msg = "删除购物车成功"
	return nil
}

func (h *Cart) GetAll(ctx context.Context, request *cart.CartFindAll, response *cart.CartAll) (err error) {
	cartAll, err := h.CartDataService.FindAllCart(request.UserId)
	if err != nil {
		return err
	}
	for _,v := range cartAll {
		cartInfo := &cart.CartInfo{}
		if err := common.SwapTo(v, cartInfo); err !=  nil {
			return err
		}
		response.CartInfo = append(response.CartInfo, cartInfo)
	}
	return nil
}


